package ynu.edu.user.controller;

import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import ynu.edu.common.domain.PageDTO;
import ynu.edu.common.domain.R;
import ynu.edu.common.exception.BadRequestException;
import ynu.edu.common.utils.BeanUtils;
import ynu.edu.common.utils.CollUtils;
import ynu.edu.common.utils.UserContext;
import ynu.edu.user.domain.dto.AddressDTO;
import ynu.edu.user.domain.po.Address;
import ynu.edu.user.domain.vo.AddressQuery;
import ynu.edu.user.service.IAddressService;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;


@RestController
@RequestMapping("/addresses")
@RequiredArgsConstructor
@Api(tags = "收货地址管理接口")
public class AddressController {

    private final IAddressService addressService;

    @ApiOperation("新增收货地址")
    @PostMapping
    public R<Void> createAddress(@Valid @RequestBody AddressDTO addressDTO) {
        addressService.createAddress(addressDTO);
        return  R.ok();
    }

    @ApiOperation("修改收货地址")
    @PutMapping("/{id}")
    public R<Void> updateAddress(@ApiParam("地址id") @PathVariable("id") Long id, @Valid @RequestBody AddressDTO addressDTO) {
        addressService.updateAddress(id, addressDTO);
        return  R.ok();
    }

    @ApiOperation("删除收货地址")
    @DeleteMapping("/{id}")
    public R<Void> deleteAddress(@ApiParam("地址id") @PathVariable("id") Long id) {
        addressService.removeById(id);
        return R.ok();
    }

    @ApiOperation("根据id查询地址")
    @GetMapping("/{id}")
    public R<Address> findAddressById(@ApiParam("地址id") @PathVariable("id") Long id) {
        return  R.ok(addressService.findAddressById(id));
    }

    @ApiOperation("查询当前用户地址列表")
    @GetMapping
    public R<List<Address>> findMyAddresses() {
        return R.ok(addressService.findMyAddresses());
    }

    @ApiOperation("设置默认地址")
    @PutMapping("/{id}/default")
    public R<Void> setDefaultAddress(@ApiParam("地址id") @PathVariable("id") Long id) {
        addressService.setDefaultAddress(id);
        return R.ok();
    }

    @ApiOperation("查询默认地址")
    @GetMapping("/default")
    public R<AddressDTO> findDefaultAddress() {
        return R.ok(addressService.findDefaultAddress());
    }

    @ApiOperation("分页查询用户地址")
    @GetMapping("/page")
    public R<PageDTO<Address>> findAllAddresses(AddressQuery addressQuery) {
        return R.ok(addressService.findAllAddresses(addressQuery));
    }
}
